import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { HomeListItem } from "../../../pages/home/homeSlice";
interface CarState {
  loading: boolean;
  car: CarItem[];
}

export interface CarItem {
  url: string;
  title: string;
  desc: string;
  price: number;
  id: string;
  count: number;
  isChecked: boolean;
}

const initialState: CarState = {
  loading: false,
  // car: JSON.parse(localStorage.getItem('car') || '[]'),
  car: []
};

const carSlice = createSlice({
  name: "carSlice",
  initialState,
  reducers: {
    addCar(state, action: PayloadAction<HomeListItem>) {
      const result = state.car.find((v) => v.id === action.payload.id);
      if (result) {
        result.count++;
      } else {
        state.car.push({
          ...action.payload,
          count: 1,
          isChecked: false,
        });
      }
    },
    addCarCount(state, action: PayloadAction<CarItem>) {
      const result = state.car.find((v) => v.id === action.payload.id);
      result && result.count++; 
    },
    subCarCount(state, action: PayloadAction<CarItem>) {
      const result = state.car.find((v) => v.id === action.payload.id);
      result && result.count--; 
    },
    deleteCar(state, action: PayloadAction<CarItem>) {
      state.car = state.car.filter(v => v.id !== action.payload.id)
    },
    switchCarCheck(state, action: PayloadAction<CarItem>) {
      const result = state.car.find((v) => v.id === action.payload.id);
      if(result) {
        result.isChecked = !result.isChecked
      }
    }
  },
});

export const { addCar, addCarCount, subCarCount, deleteCar, switchCarCheck } = carSlice.actions;
export default carSlice;
